Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
How to create 2d array using "for" loop in Javascript?

I need to write a program that creates a 2d array in variable "numbers" in rows (5) and columns (4). The elements of the array have to be consecutive integers starting at 1 and end at 20. I have to use "for" loop.

[ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10, 11, 12 ],
[ 13, 14, 15, 16 ],
[ 17, 18, 19, 20 ],

So I came up with that:

const numbers = [];
const columns = 4;
const rows = 5;

for (let i = 0; i < rows; i++) {
    numbers [i] = [];
    for (let j = 0; j < columns; j++){
        numbers  [i][j] = j + 1;
    }
}
console.log(numbers); 

But the result of this is five identical rows, like this:

      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ],
      [ 1, 2, 3, 4 ]

Do you have any idea how to fix it? How to make second row starting from 5?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Looks like in the second loop, you should do numbers [i][j] = j * i; instead

about 4 years ago · Juan Pablo Isaza Denunciar

0

Every time the outer for loop starts a new iteration, j is reset back to 0, which is why you keep getting rows starting with 1.

To fix this, you could declare a variable outside of the for loops that tracks the current number, and use that instead of j like so:

const numbers = [];
const columns = 4;
const rows = 5;
let currNum = 0;

for (let i = 0; i < rows; i++) {
    numbers [i] = [];
    for (let j = 0; j < columns; j++){
        currNum++;
        numbers  [i][j] = currNum;
    }
}
console.log(numbers); 
about 4 years ago · Juan Pablo Isaza Denunciar

0

Here is some updated code. You need to add i*columns to every value

const numbers = [];
const columns = 4;
const rows = 5;

for (let i = 0; i < rows; i++) {
    numbers[i] = [];
    for (let j = 0; j < columns; j++){
        numbers[i][j] = j + 1 + (i*columns);
    }
}
console.log(numbers); 

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda